package com.dora.algorithm.leetcode;

/**
 *
 * Definition for singly-linked list.
 * public class ListNode {
 *   int val;
 *   ListNode next;
 *   ListNode() {}
 *   ListNode(int val) { this.val = val; }
 *   ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 *
 * @author hanchen
 */
public class Q2_AddTwoNumbers {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        ListNode l5 = new ListNode(3);
        ListNode l3 = new ListNode(4, l5);
        ListNode l1 = new ListNode(2, l3);

        ListNode l6 = new ListNode(4);
        ListNode l4 = new ListNode(6, l6);
        ListNode l2 = new ListNode(5, l4);
        ListNode result = addTwoNumbers(l1, l2);
        System.out.println(result);
    }

    /**
     * 两数之和
     *
     * @param l1 l1
     * @param l2 l2
     * @return {@link ListNode}
     */
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode current = dummy;
        int carry = 0;
        while (l1 != null || l2 != null) {
            int sum = carry;
            if (l1 != null) {
                sum += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                sum += l2.val;
                l2 = l2.next;
            }
            current.next = new ListNode(sum % 10);
            current = current.next;
            carry = sum / 10;
        }
        if (carry > 0) {
            current.next = new ListNode(carry);
        }
        return dummy.next;
    }

}
